import 'package:dio/dio.dart';
import 'package:enjoy_three/utils/eventbus.dart';
import 'package:enjoy_three/utils/http.dart';
import 'package:enjoy_three/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:image_picker/image_picker.dart';
class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});
  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  //渲染详情页信息
Map userInfo = {'avatar': '', 'nickName': '', 'id': ''};
final TextEditingController _controller = TextEditingController();
@override
void initState(){
  super.initState();
  setState(() {
    userInfo= widget.userInfo;
    _controller.text = userInfo['nickName'];
  });
}
//上传图像
void showBottom () async {
  showModalBottomSheet(context: context, builder:(context){
    return SizedBox(
      height: 200,
      child: Column(
        children: [
          ListTile(
          leading: Icon(Icons.camera_alt),
          title: const Text('拍照'),
          onTap: ()async{
            final ImagePicker picker = ImagePicker();
               final XFile? photo = await picker.pickImage(source: ImageSource.camera);
            if(photo != null){
             selectAvtar(photo.path);
            }
          },
          ),
          ListTile(
            leading: Icon(Icons.photo),
            title: Text('相册'),
            onTap: ()async{
              final ImagePicker picker = ImagePicker();
                    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
              if(image != null){
                selectAvtar(image.path);
              }
            },
          )
        ],
      ),
    );
  });
}
//上传图像调用接口
selectAvtar(String imageType) async{
try{
       FormData formData = FormData.fromMap({
          "file": await MultipartFile.fromFile(imageType),
          "type": "avatar",
        });
        var res = await http.post('/upload', formData);
        if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
        setState(() {
          userInfo['avatar'] = res['data']['url'];
        });
        ToastUtil.showSuccess('上传图片成功!');
}finally{
  Navigator.pop(context);
 }
}

//修改昵称
void updataName()async {
  if(_controller.text.isEmpty){
    return ToastUtil.showError('昵称不能为空!');
  }
  try{
  await http.put('/userInfo', {"nickName":_controller.text});
  setState(() {
    userInfo['nickName'] = _controller.text;
    ToastUtil.showSuccess('修改昵称成功!');
  });
  }catch(e){
    ToastUtil.showError('修改昵称失败!');
  }

}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: IconButton(onPressed: (){
          eventBus.fire(backMine());
          Navigator.pop(context);
        }, icon: Icon(Icons.arrow_back)),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                
                  children: [
                  GestureDetector(
                    onTap: (){
                      showBottom();
                    },
                    child:  ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        // 头像
                        child:userInfo['avatar'] != '' ? Image.network(userInfo['avatar'],width: 50,height: 50,): Image.asset('images/avatar_1.jpg',
                                width: 30, height: 30)
                                ),
                  ),
                    const Icon(Icons.arrow_forward_ios, size: 12),
                    
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _controller,
                  decoration:  InputDecoration(
                      hintText: userInfo['nickName'] ??'请输入昵称', border: InputBorder.none),
                  textAlign: TextAlign.right,
                  onEditingComplete: () {
                    updataName();
                  },
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}